<?php
/**
 * @version		$Id: myprojid.php 2011.08.11 thierry $
 * @package		site.models
 * @subpackage	com_projid
 * @copyright	Copyright (C) 2011 Pojid All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */
//view/model/projid
defined('_JEXEC') or die('Restricted access');
class Projid 
{
	protected $_item;

	protected $_name;
	protected $_result;
	protected $_myid;


	function __construct($name){
		$this->_name = $name;
		$this->getResult();
		$this->setMyID();
		}
	function setMyID(){
		$this->_myid= rand();
		}
	
	function getQuery() {
		$name = $this->_name;
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from('#__projid_server');
		$query->leftJoin('#__projid_requete on #__projid_server.id_serv=#__projid_requete.server_id ') ;
		$query->leftJoin('#__projid_graphic ON #__projid_requete.id_que=#__projid_graphic.requete_id');
		$query->where('#__projid_requete.id_que=#__projid_graphic.requete_id');
		$query->where('#__projid_graphic.nom= "'. (string) $name.'";');
	$db->setQuery((string)$query);
			$entries = $db->loadObject();
			$this->_item=$entries;
	return $this->_item;
	
		}
	//Retourne le contenu de la requete
	 function getResult(){
		$item = $this->getQuery();
		//
		//$item = $this->_item;
		$option = array(
		'host' 		=> $item->host,
		'database'	=> $item->base,
		'user' 		=> $item->user,
		'password' 	=> $item->password,
		'driver' 	=> $item->driver
		//'prefix'	=> $prefix
		);

		$db = JDatabase::getInstance($option);
		$jAp=& JFactory::getApplication();

		if (JError::isError($db)) {
					header('HTTP/1.1 500 Internal Server Error');
					jexit('Database Error: ' . (string) $db);
				}
		if ($db->getErrorNum() > 0) {
			JError::raiseError(500, JText::sprintf('JLIB_UTIL_ERROR_CONNECT_DATABASE', $db->getErrorNum(), $db->getErrorMsg()));
				}

		$query = $item->requete;
		$db->setQuery($query);
		$db->query();
		
		$result = $db->loadAssocList();
		
		if (is_null($posts=$db->loadRowList())) {
			$jAp->enqueueMessage(nl2br($db->getErrorMsg()),'error'); 
			return;
		}
		return $this->_result=$result;
	}

//CReate the array
function getTreeArray(){ 
	$result = $this->_result;
	$n=0;
	
	foreach($result as $element):
		if($n<1){
			$keys=array_keys($element);
			}
		$n++;
	endforeach;
	//TO manage empty field
	$arrayZ=array();
	$arrayX=array();
	$arrayY=array();
	$treearray=array();
	$c=0;
	foreach($result as $element):
		$c++;	
		$i=0;
		foreach($element as $entry):
			$i++;
			if(count($keys)==3){
				switch($i){
					case 1://Prod
						if(!in_array($entry,$arrayZ)){
						array_push($arrayZ,$entry);
						}
						break;
					case 2://Month
						if(!in_array($entry,$arrayX)){
						array_push($arrayX,$entry);
						}
						break;
						}//end switch
				}//end if 
			else{
				if($i==1){//Month
					if(!in_array($entry,$arrayX)){
						array_push($arrayX,$entry);
						}//end if
				}//endif
			}//end else
		endforeach;
	endforeach;

		array_push($treearray,$arrayX,$arrayZ,$keys);

	return $treearray;
	}

function getEmptyArray(){
	$treearray = $this->getTreeArray();
	$result= array();
	$rnk=array();
	$temparray=array();
	$arrayX=$treearray[0];
	$arrayZ=$treearray[1];
	$keys=$treearray[2];
	foreach($arrayZ as $prod){
		foreach($arrayX as $date){
			$temparray[$keys[0]]=$prod;
			$temparray[$keys[1]]=$date;
			$temparray[$keys[2]]=0;
			array_push($result,$temparray);
			}
		}
	array_push($rnk,$result,$keys);
	return $rnk;
	}

function getCompleteArray(){
	$rnk = $this->getEmptyArray();
	$RArray = $this->_result;
	//$rnk issue de madeEmptyArray()
	//SRArray issue de connectNGetArray($source)
	//$key=array();
	//$result=array();
	//$prod=array();
	//$date=array();
	//$val=array();
	$i=0;
	$keys=$rnk[1];
	$result=$rnk[0];
		$prod=$keys[0];
		$date=$keys[1];
		if (!isset($keys[2])){$keys[2]="";}
		$val=$keys[2];	
		foreach($RArray as $source){
			foreach($result as &$dest){
				$i++;
				if($source[$prod]==$dest[$prod] && $source[$date]==$dest[$date]){
					$dest[$val]=$source[$val];
					}
				}
			}
	return $result;
	}

function getVal(){
	$final = $this->getCompleteArray();
	$arrayY=array();
	foreach($final as $temp){
		$recup=end($temp);
		array_push($arrayY,$recup);
		}
	return $arrayY;
	}

function getJson(){
	$test = $this->getTreeArray();
	$val =$this->getVal();
	
	$type = $this->_item->type;

	if($type=='line'){
	$headerfield = 'date';
	$prod=$test[1];
	$date=$test[0];
}else{
	$headerfield = 'name';
	$prod=$test[0];
	$date=$test[1];
}

	//$val= $arrayY;
	//$prod=$test[1];
	//$date=$test[0];

	$v=0;
	$my_value='[';
		for($i=0; $i<count($date);$i++){
		$my_value.= '{"'.$headerfield.'":"'.$date[$i].'",';
		for($n = 0; $n<count($prod);$n++){
			$my_value.='"'.$prod[$n].'":'.$val[$v].'';
			if($n==count($prod)-1){}
				else{
				$my_value.=',';
				}
				$v++;
			}
			if($i==count($date)-1){
			$my_value.="}";
			}
		else{
		$my_value.="},";
		}
	}
	$my_value.=']';

	$trans_value = json_decode($my_value);
	$res = json_encode($trans_value);
	return $res;
	}

function getType(){
	return $this->_item->type;
	}

#####################
function getJS(){
		$myjs = $this->createJsStore();
		$type = $this->_item->type;
		if($type=="line"||$type=="bar"||$type=="pie"){

			$myjs.= $this->generateGraph();
			
			}else{

			$myjs.= $this->generateGrid();
			
			}
		$result = "<script type=\"text/javascript\">".$myjs."</script> ";
		return $result;
		}
	
	function generateGraph(){

		$mygraph= $this->generateChart();
		
		$mygraph.= $this->generateAddon();

		$mygraph.= $this->generateAxe(); 
    
		$mygraph.= $this->generateSerie();
	return $mygraph;
		}

	//Fonction de création du store JS
	function createJsStore(){

	$id = $this->_item->id_gra;

	$field_name=$this->generateField();
	$json = $this->getJson();
	$name = $this->_name;
	$type=$this->_item->type;

if($type=='line'){
	$headerfield = 'date';
}else{
	$headerfield = 'name';
}


	
	$myfile=
		<<<EOT
Ext.require([
	    'Ext.grid.*',
	    'Ext.data.*',
	    'Ext.util.*',
	    'Ext.state.*'
	]);

EOT;
		//Construction du model de donnée
	$myfile .= <<<EOT

Ext.onReady(function() {

var mydata = { 
	result:$json
	};

 Ext.define('Data',
	{ extend:'Ext.data.Model',
	fields:['$headerfield',$field_name});
	var store = new Ext.data.Store({
		autoLoad: true,
		model:'Data',
		data: mydata,
		proxy:{
		type:'memory',
		
		reader:{
		type: 'json',
		root:'result'
		}
	}
});
EOT;
	return $myfile;
	}

	//
	function generateChart(){
		$width=$this->_item->width;
		$height=$this->_item->height;
		$title=$this->_item->desc_gra;
$id =$this->_myid;
		$mygraph= <<<EOT
		Ext.create('Ext.chart.Chart', {
				width: $width,
		 		height:$height,
		 		title: '$title',
				renderTo: '$id',
			store:store,
EOT;
	return $mygraph;
	}
///
	function generateAddon(){
		$type=$this->_item->type;
		switch($type){
		case "line":
			$addon = <<<EOT
			legend: {
                position: 'right'
            },
			insetPadding: 30,
			animate: false,
EOT;
			return $addon;
			break;
		case "pie":
			$addon = <<<EOT
			legend: {
                position: 'right'
            },
			theme: 'Base:gradients',
			 animate: true,
EOT;
			return $addon;
			break;
		case "bar":
			$addon = <<<EOT
			animate: true,
EOT;
			return $addon;
			break;
		}
	}
///
//Fonction de generation des axes ..
	function generateAxe(){
		$type=$this->_item->type;

//$one_fields=generateField($chart->getSource()->getArrayZ());
	$one_fields= $this->generateField();
	switch($type){
		case "line":		######### Line
			
			$myaxe= <<<EOT
			axes: [{
                type: 'Numeric',
                minimum: 0,
                adjustMaximumByMajorUnit: 0,
                position: 'left',          
				fields:[$one_fields,
   				title: false,
                grid: true,
                label: {
                    renderer: Ext.util.Format.numberRenderer('0.0'),
                    font: '10px Arial'
                }
            }, {
                type: 'Category',
                position: 'bottom',
				fields: ['date'],
                title: false,
                label: {
                	rotate: {
                    	degrees: 315
            			},
                    font: '11px Arial', 
                	}
            	}],
EOT;
		return $myaxe;
		break;
		case "pie":			########## Pie
			break;
		case "bar":			########## Bar
			$titre=array();

///////////////////////
//Desactiver pour le moment 
		//	$titre=$chart->getSource()->getCol_name();
		//	$titre_X=$titre[2];
		//	$titre_Y=$titre[0];
/////////////////////////
$arrays = $this->getTreeArray();

			$month =array();
			$month = $arrays[0];

			$field_month=current($month);
			
			$myaxe= <<<EOT
			axes: [{
        type: 'Numeric',
        position: 'bottom',
        minimum: 0,
                adjustMaximumByMajorUnit: 0,
        fields: ['$field_month'],
        label: {
            renderer: Ext.util.Format.numberRenderer('0.0')
        },
        title: '$titre_X',
        grid: true,
        minimum: 0
    }, {
        type: 'Category',
        position: 'left',
        fields: ['name'],
        title: '$titre_Y'
    }],
EOT;
			return $myaxe;
			break;	
		}	
	}

//fonction de génération de serie
function generateSerie(){
$arrays = $this->getTreeArray();
$month = $arrays[0];
//$month = array();
//$month = $this->arrays[0];

$prod = $arrays[1];
$field_month = current($month);
	// Génération des series
	$myserie= "series: [";
	$type=$this->_item->type;
	switch($type){
		case "line":		######### Line
			
			//$prod=$chart->getSource()->getArrayZ();
			
			if($prod==null)
			{
				array_push($prod,'values');
			}
			for($i=0; $i<count($prod); $i++){
	$myserie.= <<<EOT
	{
                type: '$type',
                highlight: {
                    size: 7,
                    radius: 7,
                },
                axis: 'left',
                fill: true,
                xField: 'date',
                yField: '$prod[$i]',
                markerCfg: {
                    type: 'circle',
                    size: 4,
                    radius: 4,
                    'stroke-width': 0
                	} 
            	}    	
EOT;
				if($i==count($prod)-1){
				$myserie.= <<<EOT
]
	});
});
EOT;
				}
			else{
			$myserie.=",";
			}
	}//End of FOr
	return $myserie;
	break;
		case "pie":			######### pie
$myserie.=<<<EOT
{
			type: 'pie',
                field: '$field_month',
                showInLegend: true,
                
                tips: {
                  trackMouse: true,
                  width: 110,
                  height: 18,
                  renderer: function(storeItem, item) {
                    //calculate percentage.
                    var total = 0;
                    store.each(function(rec) {
                        total += rec.get('$field_month');
                    });
                    this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('$field_month') / total * 100) + '%');
                  }
                },
                highlight: {
                  segment: {
                    margin: 20
                  }
                },
                label: {
                    field: 'name',
                    display: 'rotate',
                    contrast: true,
                    font: '18px Arial'
                }
            }]
        
    });
});       
EOT;
return $myserie;
break;
		case "bar":			######### bar
$myserie.=<<<EOT
{
			type: 'bar',
			 
        	axis: 'bottom',
       		highlight: true,
        	tips: {
          		trackMouse: true,
          		width: 140,
          		height: 28,
          		renderer: function(storeItem, item) {
            		this.setTitle(storeItem.get('name') + ': ' + storeItem.get('$field_month') + ' $titre_X');
          			}
        		},
        	label: {
          		display: 'insideEnd',
            	field: '$field_month',
            	renderer: Ext.util.Format.numberRenderer('0'),
            	orientation: 'horizontal',
            	color: '#333',
            	'text-anchor': 'middle'
        		},
        	xField: 'name',
        	yField: ['$field_month']
    	}]
	});
});
EOT;
return $myserie;
break;
	}
}

function getHeaderJS(){

$id = $this->_myid;
	$header=<<<EOT
	<link rel="stylesheet" type="text/css" href="media/com_projid/resources/css/ext-all-without-border-box.css" />
  
	<div id='$id'></div>
EOT;
return $header;
}

//Creation du fichier js
	function generateGrid(){
		//Concaténation des chaines de caractèr
		$mygrid.=$this->beginGrid();

		$mygrid.=$this->generateColumns();
		$mygrid.=$this->endGrid();
		return $mygrid;
	}

	//Fonction de generation des champs du fichier JS
	function generateField(){
	
	$arrays = $this->getTreeArray();
	$type = $this->_item->type;

	if($type=='line'){
		$fields_name = $arrays[1];
		}else{
		$fields_name = $arrays[0];
		}
	$my_fields="";
	for ($i=0; $i<count($fields_name);$i++){
			$my_fields.="'".$fields_name[$i]."'";
			if($i==count($fields_name)-1){
				$my_fields.="]";
				$my_fields.="\n";
			}
			else{
			$my_fields.=",";	
			}
			}
	$my_fields.="\t";
	return $my_fields;
	}

	//Create the grid from an object
	function beginGrid(){
		$id= $this->_myid;
		$mygrid.= <<<EOT
Ext.create('Ext.panel.Panel',{
renderTo: '$id',
layout:'anchor',
		items:[{
			xtype:'grid',
			store:store,
			stateful:true,
EOT;
	return $mygrid;
	}
//Generate the column of the grid from the result colname 
	function generateColumns(){
		$arrays = $this->getTreeArray();
		$fields=$arrays[0];
		$keys = array_keys($this->_result[0]);
		$name = $keys[0];

		$myColumn="columns:[";
		$myColumn.="{text		:'$name',dataIndex	:'name',flex:5},";
		for($i=0; $i<count($fields);$i++){
			$myColumn.=<<<EOT
			{ text	:'$fields[$i]', dataIndex	:	'$fields[$i]',flex:5 }
EOT;
	if($i==count($fields)-1){
				$myColumn.= <<<EOT
	],
EOT;
				}
			else{
			$myColumn.=",";
			}
	}//End of FOr
	return $myColumn;
}

//Terminate the GRid 
function endGrid(){
	$name=$this->_item->desc_gra;
//$name = $this->_name;
$id= $this->_myid;
$mygrid.=<<<EOT

	title:'$name',
	
	viewConfig:{ stripeRows:true }
	}]
	});
});
EOT;
return $mygrid;
}
}
?>